package com.boot.controller;

import com.boot.entity.CourseOpen;
import com.boot.entity.Term;
import com.boot.repository.CourseOpenRepository;
import com.boot.repository.TermRepository;
import com.boot.vo.BaseMessage;
import com.boot.vo.MessageHandler;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/courseOpen")
public class CourseOpenController {

    @Autowired
    private CourseOpenRepository courseOpenRepository;

    @Autowired
    private TermRepository termRepository;

    @GetMapping("list")
    private BaseMessage<?> list() {
        List<CourseOpen> all = courseOpenRepository.findAll();
        Set<Integer> ids = all.stream().map(CourseOpen::getTermId).collect(Collectors.toSet());
        List<Term> terms = termRepository.findByTermidIn(ids);
        Map<Integer, String> id2name = terms.stream().collect(Collectors.toMap(Term::getTermid, Term::getName));
        all.forEach(e->e.setCourseName(id2name.get(e.getTermId())));
        return MessageHandler.createSuccessVo(all, "success");
    }


    @PostMapping
    public BaseMessage<?> addOrUpdate(@RequestBody CourseOpen courseOpen) {
        courseOpenRepository.save(courseOpen);
        return MessageHandler.createSuccessVo(courseOpen.getId() != null ? "修改成功！" : "保存成功！");
    }

    @DeleteMapping("/{id}")
    public BaseMessage<?> del(@PathVariable Integer id) {
        courseOpenRepository.deleteById(id);
        return MessageHandler.createSuccessVo("删除成功！");
    }

}
